package com.hxkj.service.impl;


import com.hxkj.dao.ResourcesDao;
import com.hxkj.domain.enums.FileType;
import com.hxkj.domain.enums.ResourcesExceptionEnum;
import com.hxkj.domain.enums.ResourcesSuccessEnum;
import com.hxkj.domain.po.Resources;
import com.hxkj.domain.po.ResourcesTree;
import com.hxkj.service.ResourcesService;
import com.hxkj.utils.MD5Utils;
import com.integral.mall.file.po.SysFile;
import com.integral.mall.file.service.SysFileService;
import com.integral.mall.file.storage.sftp.SFTPStorage;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.util.DateUtils;
import com.platform.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 网站资源实现类
 * <p>
 * Created by yaosy on 2018年6月8日
 */
@Service
@Slf4j
public class ResourcesImpl implements ResourcesService {

    @Autowired
    private ResourcesDao resourcesDao;

    @Resource
    private SysFileService sysFileService;

    @Value("${cms.resourcesPath}")
    private String uploadPath ;

    @Value("${storage.sftp.fileRoot}")
    private String fileRoot ;

    @Value("${cms.pathUrl}")
    private String pathUrl;

    @Value("${cms.tmpRes}")
    private String tmpRes;

    @Value("${cms.basePath}")
    private String basePath;


    @Override
    public ResultDataStruct<Resources> saveResources(Resources resources) {
        ResultDataStruct<Resources> resourcesResultDataStruct = new ResultDataStruct<>();
        //判断数据库是否存在相同的文件名,有则抛出异常
        SysFile sysFilePrefix = null;
        String suffix =  FilenameUtils.getExtension(resources.getPath())==null?"":FilenameUtils.getExtension(resources.getPath());
        int type = getType(suffix);
        if(resources.getIsDirectory()==2){//上传情况
            Resources newResources = new Resources();
            newResources.setParentId(resources.getParentId());
            newResources.setResourcesName(FilenameUtils.getName(resources.getPath()));
            newResources.setDelTag((byte)0);
            List<Resources> resourcesList = resourcesDao.get(newResources);
            if(resourcesList != null && resourcesList.size() > 0){
                resourcesResultDataStruct.setCode(ResourcesExceptionEnum.RESOURCES_EXISTS_FAILED.getCode());
                resourcesResultDataStruct.setMessage(ResourcesExceptionEnum.RESOURCES_EXISTS_FAILED.getMsg());
                return resourcesResultDataStruct;
            }
            resourcesResultDataStruct = saveUploadContent(resources);
        }else{//手动新增情况
            //根据parentId获取目录的路径;如果是保存的文件内容,则反向生成html、并上传多对应的sftp文件服务器上
            String md5Name = combineResourceName(FilenameUtils.getBaseName(resources.getResourcesName()));


            Resources parentResources = resourcesDao.get(resources.getParentId());
            try {
                sysFilePrefix = writeHTMLFile(md5Name +"."+ FilenameUtils.getExtension(resources.getResourcesName()),resources.getSource(), resources.getSiteId(),parentResources.getPath());
            } catch (IOException e) {
                resourcesResultDataStruct.setCode(ResourcesExceptionEnum.RESOURCES_CONENT_ERROR.getCode());
                resourcesResultDataStruct.setMessage(ResourcesExceptionEnum.RESOURCES_CONENT_ERROR.getMsg());
                return resourcesResultDataStruct;
            }
            if(sysFilePrefix != null){
                String prefixPath =  sysFilePrefix.getFilePath();
                if(StringUtils.isNotEmpty(prefixPath)){
                    if(prefixPath.startsWith(basePath)) {
                        String filenamePath = prefixPath.substring(fileRoot.length(), prefixPath.length());
                        resources.setPath(filenamePath);
                    }else{
                        resources.setPath(prefixPath);
                    }
                }
                resources.setResourcesName(resources.getResourcesName());
                resources.setResourcesAlias(md5Name);
                double d = sysFilePrefix.getFileSize()==null?resources.getSource().length()/1024:sysFilePrefix.getFileSize()/1024;
                resources.setSize(new Double(d).longValue());
                //截取文件路径
                if(sysFilePrefix.getFilePath() != null){
                    String filePath = sysFilePrefix.getFilePath().substring(0, sysFilePrefix.getFilePath().lastIndexOf("/")+1);
                    resources.setFileName(filePath);
                }
                resourcesDao.save(resources);
                resourcesResultDataStruct.setData(resources);
                resourcesResultDataStruct.setCode(200);
                return resourcesResultDataStruct;
            }else{
                resourcesResultDataStruct.setMessage("保存资源文件失败!");
                resourcesResultDataStruct.setCode(402);
            }
        }

        return resourcesResultDataStruct;
    }

    //写入文件并上传
    /**
     * 写文件
     * @param
     *
     * @throws
     */
    public  SysFile writeHTMLFile(String fileName, String source , Long siteId , String parentPath) throws IOException {
        // 先读取原有文件内容，然后进行写入操作
        boolean flag = false;
        String filein = source;
        String temp = "";
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            File fi = new File(System.getProperty("java.io.tmpdir")+"/"+tmpRes);
            if(!fi.exists()) fi.mkdir();
            String path = System.getProperty("java.io.tmpdir")+"/"+tmpRes+DateUtils.toDateToString(new Date(),"yyyyMMddHHmmss")+".html";
            // 文件路径
            File file = new File(path);
            if(!file.exists()) file.createNewFile();
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();
            // 保存该文件原有的内容
            for (int j = 1; (temp = br.readLine()) != null; j++) {
                buf = buf.append(temp);
                buf = buf.append(System.getProperty("line.separator"));
            }
            buf.append(filein);
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            InputStream s =  new FileInputStream(new File(path));
            String type = FilenameUtils.getExtension(fileName);
            fileName = FilenameUtils.getBaseName(fileName);
            SysFile sysFilePrefix = sysFileService.upload(fileName, type,parentPath ,s);
            return sysFilePrefix;
        } catch (IOException e1) {
            e1.printStackTrace();
            log.error("写入文件失败!");
        } finally {
            if (pw != null) pw.close();
            if (fos != null) fos.close();
            if (br != null) br.close();
            if (isr != null) isr.close();
            if (fis != null) fis.close();
        }
        return null;
    }


    @Override
    public ResultDataStruct<Resources> saveResourcesFolder(Resources resources,SFTPStorage sftpStorage) {
        ResultDataStruct<Resources> resourcesResultDataStruct = new ResultDataStruct<>();
        try{
            ChannelSftp channelSftp = sftpStorage.getSftpPool().getClient();
            //初始化时,实际没有生产该站点文件夹,此处需判断该站点下是否存在根目录,不存在则创建
            SftpATTRS attrs = null;
            String sitePath = null;
            if(fileRoot.startsWith(basePath))
                sitePath = uploadPath + "/" + resources.getSiteId();
            else
                sitePath = uploadPath + "/" + resources.getSiteId();
            try{
                log.error("当前生成的目录为{}",sitePath);
                channelSftp.cd(sitePath);
                attrs = channelSftp.stat(sitePath);
            }catch(Exception e){

            }
            if(attrs==null){
                channelSftp.mkdir(sitePath);
            }

            //存入数据库,并上传文件到sftp服务器
            Resources templteRoot = resourcesDao.get(resources.getParentId());
            String oldPath = "";
            if(templteRoot!=null){
                oldPath = templteRoot.getPath()+resources.getResourcesName()+"/";
                resources.setPath(oldPath);
                resources.setFileName(templteRoot.getPath());
                resources.setParentId(templteRoot.getResourcesId());
            }else{//此处考虑未创建templet
                templteRoot = new Resources();
                try {
                    oldPath = uploadPath;
                    channelSftp.mkdir(uploadPath);
                    templteRoot.setPath(uploadPath);
                }catch (Exception e){}
            }
            Resources searchResource = new Resources();
            searchResource.setSiteId(resources.getSiteId());
            searchResource.setPath(resources.getPath());
            String createPath = templteRoot.getPath()+resources.getResourcesName();
            //判断目录是否存在,存在则不需要添加
            Resources resourced = new Resources();
            resourced.setSiteId(resources.getSiteId());
            resourced.setPath(templteRoot.getPath()+resources.getResourcesName()+"/");
            log.error(templteRoot.getPath()+resources.getResourcesName()+"/");
            List<Resources>  resourcesList =  resourcesDao.get(resourced);
            if(resourcesList != null && resourcesList.size() >0){
                boolean flag = false;
                for(Resources r : resourcesList){
                    if(r.getResourcesName().equals(resources.getResourcesName())){
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    resourcesResultDataStruct.setMessage(ResourcesExceptionEnum.RESOURCES_EXISTS_FAILED.getMsg());
                    resourcesResultDataStruct.setCode(ResourcesExceptionEnum.RESOURCES_EXISTS_FAILED.getCode());
                    return resourcesResultDataStruct;
                }
            }
            log.error("路径名称为{}",templteRoot.getPath()+resources.getResourcesName());
            channelSftp.mkdir(templteRoot.getPath()+resources.getResourcesName());
            resourcesDao.save(resources);
            sftpStorage.getSftpPool().returnClient(channelSftp);
            resourcesResultDataStruct.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
            resourcesResultDataStruct.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
            resourcesResultDataStruct.setData(resources);
            return resourcesResultDataStruct;
        }catch(Exception e){
            e.printStackTrace();
            log.error("创建资源目录失败!");
            resourcesResultDataStruct.setCode(ResourcesExceptionEnum.FAIL_RESOURCES_ERROR.getCode());
            resourcesResultDataStruct.setMessage(ResourcesExceptionEnum.FAIL_RESOURCES_ERROR.getMsg());
            return resourcesResultDataStruct;
        }
        //return resourcesResultDataStruct;
    }

    protected void initInsertTemplte(Resources resource){
        Resources newresources = new Resources();
        newresources.setParentId(-1L);
        newresources.setSiteId(resource.getSiteId());
        List<Resources> templetList = resourcesDao.get(newresources);
        if(templetList.size() == 0){
            newresources = new Resources();
            newresources.setParentId(-1L);
            newresources.setLastModifiedDate(resource.getLastModifiedDate());
            newresources.setDelTag(resource.getDelTag());
            newresources.setCreateor(resource.getCreateor());
            newresources.setCreateTime(resource.getCreateTime());
            newresources.setModifyBy(resource.getModifyBy());
            newresources.setPath(uploadPath+"/"+resource.getSiteId()+"/");
            newresources.setFileName(uploadPath+"/"+resource.getSiteId()+"/");
            newresources.setSize(0L);
            newresources.setResourcesName("资源根目录");
            newresources.setSiteId(resource.getSiteId());
            newresources.setStatus(resource.getStatus());
            newresources.setIsDirectory(resource.getIsDirectory());
            newresources.setSource("");
            newresources.setResourcesAlias(MD5Utils.getMd5ByResources());
            resourcesDao.save(newresources);
        }
    }


    @Override
    public ResultDataStruct getResourcesTree(Resources resources) throws Exception {
        ResultDataStruct resultDataStruct = new ResultDataStruct();
        List<ResourcesTree> resourcesList = new ArrayList<>();
        try{
            //当无根目录模板时,初始化根目录
            initInsertTemplte(resources);
            if (StringUtils.isBlank(resources.getKeyword())){
                //获取功能树父级
                Resources parentResources = new Resources();
                parentResources.setParentId(-1L);
                parentResources.setSiteId(resources.getSiteId());
                Resources newParentTemplet = resourcesDao.selectResourcesFolderPath(parentResources);
                ResourcesTree resourcesTree = new ResourcesTree();
                if(newParentTemplet!=null) {
                    resources.setSiteId(newParentTemplet.getSiteId());
                    resources.setParentId(newParentTemplet.getParentId());
                    resourcesTree.setResourcesId(newParentTemplet.getResourcesId());
                    resourcesTree.setResourcesName(newParentTemplet.getResourcesName());
                    resourcesTree.setChildren(initTree(newParentTemplet.getResourcesId(), newParentTemplet));
                    resourcesTree.setLastModifiedDate(newParentTemplet.getLastModifiedDate());
                    resourcesTree.setFilename(newParentTemplet.getFileName() == null ? "" : newParentTemplet.getFileName());
                    resourcesTree.setPath(newParentTemplet.getPath());
                    resourcesTree.setSource("");
                    resourcesTree.setSize(newParentTemplet.getSize()/1024);
                    resourcesTree.setSiteId(newParentTemplet.getSiteId());
                    resourcesTree.setResourcesAlias(newParentTemplet.getResourcesAlias()==null?"":newParentTemplet.getResourcesAlias());
                    resourcesList.add(resourcesTree);
                }else{//无数据时,只给根模板数据
                    Resources newtemplet = new Resources();
                    newtemplet.setParentId(-1L);
                    List<Resources>  parentTempletList = resourcesDao.get(newtemplet);
                    if(parentTempletList.size()>0){
                        Resources parentTemp = parentTempletList.get(0);
                        resourcesTree.setResourcesId(parentTemp.getResourcesId());
                        resourcesTree.setResourcesName(parentTemp.getResourcesName());
                        resourcesTree.setChildren(new ArrayList<>());
                        resourcesTree.setLastModifiedDate(parentTemp.getLastModifiedDate());
                        resourcesTree.setFilename(parentTemp.getFileName() == null ? "" : parentTemp.getFileName());
                        resourcesTree.setPath(parentTemp.getPath());
                        resourcesTree.setSize(newParentTemplet.getSize()/1024);
                        resourcesTree.setResourcesAlias(parentResources.getResourcesAlias());
                        resourcesTree.setSource("");
                        resourcesTree.setSiteId(parentTemp.getSiteId());
                        resourcesTree.setResourcesAlias(parentResources.getResourcesAlias()==null?"":parentResources.getResourcesAlias());
                        resourcesList.add(resourcesTree);
                    }
                }
            }else{
                //模糊查询的模板
                Resources resources1 = new Resources();
                resources1.setSiteId(resources.getSiteId());
                resources1.setKeyword(resources.getKeyword());
                resources1.setDelTag((byte)0);
                resources1.setStatus((byte)0);
                List<Resources> resources2 = resourcesDao.get(resources1);
                //定义一个set集合去重复
                Set<Resources> resourcesSet = new HashSet<>();
                for (Resources res : resources2){
                    getParent(res.getResourcesId());
                    resourcesSet.add(globalResources);
                }
                for (Resources res : resourcesSet){
                    ResourcesTree tree = new ResourcesTree();
                    tree.setFilename(res.getFileName()==null?"":res.getFileName());
                    tree.setLastModifiedDate(res.getLastModifiedDate());
                    tree.setPath(res.getPath()==null?"":res.getPath());
                    tree.setResourcesId(res.getResourcesId());
                    tree.setResourcesName(res.getResourcesName()==null?"":res.getResourcesName());
                    tree.setSize(res.getSize()==null?0L:res.getSize());
                    tree.setSource(res.getSource()==null?"":res.getSource());
                    tree.setResourcesAlias(res.getResourcesAlias());
                    tree.setSiteId(res.getSiteId());
                    tree.setIsDirectory(res.getIsDirectory());
                    tree.setParentId(res.getParentId());
                    tree.setChildren(initTree(res.getResourcesId(),res));
                    tree.setResourcesAlias(res.getResourcesAlias()==null?"":res.getResourcesAlias());
                    resourcesList.add(tree);
                }
            }
            resultDataStruct.setData(resourcesList);
        }catch(Exception e){
            e.printStackTrace();
            log.info("查询资源列表错误");
            resultDataStruct.setCode(ResourcesExceptionEnum.RESOURCES_GET_ERROR.getCode());
            resultDataStruct.setMessage(ResourcesExceptionEnum.RESOURCES_GET_ERROR.getMsg());
            return resultDataStruct;
        }
        resultDataStruct.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
        resultDataStruct.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
        resultDataStruct.setData(resourcesList);
        return resultDataStruct;
    }

    //自定义获取任意一个模板的最顶级的父模板的递归方法
    //定义一个全局变量存值
    private  Resources globalResources = new Resources();
    private  Resources getParent(Long id) {
        globalResources = resourcesDao.get(id);
        if (resourcesDao.get(globalResources.getParentId()).getParentId() != -1) {
            getParent(globalResources.getParentId());
        }
        return globalResources;
    }
    private List<ResourcesTree> initTree(long id, Resources resources) {
        List<ResourcesTree> resourceTrees = new ArrayList<ResourcesTree>();
        Resources resou = new Resources();
        resou.setParentId(id);
        resou.setSiteId(resources.getSiteId());
        resou.setResourcesName("");
        List<Resources> authResources = resourcesDao.getResourcesTree(resou);
        if (authResources != null && authResources.size() != 0) {
            for (Resources auf : authResources) {
                ResourcesTree resourcesTree = new ResourcesTree();
                resourcesTree.setResourcesName(auf.getResourcesName());
                resourcesTree.setResourcesId(auf.getResourcesId());
                resourcesTree.setParentId(auf.getParentId());
                resourcesTree.setSource("");
                resourcesTree.setPath(auf.getPath()==null?"":auf.getPath());
                resourcesTree.setFilename(auf.getFileName());
                resourcesTree.setLastModifiedDate(auf.getLastModifiedDate());
                resourcesTree.setSize(auf.getSize() == null ?0: getSize(auf.getSize()));
                resourcesTree.setIsDirectory(auf.getIsDirectory());
                resourcesTree.setChildren(initTree(auf.getResourcesId(), resources));
                resourcesTree.setSiteId(auf.getSiteId());
                resourcesTree.setResourcesAlias(auf.getResourcesAlias()==null?"":auf.getResourcesAlias());
                resourceTrees.add(resourcesTree);
            }
        }
        return resourceTrees;
    }


    protected double getSize(double size) {
        BigDecimal bg = new BigDecimal(size/1024);
        double f1 = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    @Override
    public ResultMessageStruct modify(Resources resources,SFTPStorage sftpStorage) throws Exception {
        ResultMessageStruct resul = new ResultMessageStruct();
        ChannelSftp channelSftp = sftpStorage.getSftpPool().getClient();
        try{
            //如果isDirectory为0,则为文件夹;为1,则为内容
            if(resources.getIsDirectory()==0){
                //如果是顶级父目录,则不允许修改
                Resources parentResources = resourcesDao.get(resources.getResourcesId());
                //此处考虑如果是文件名转为文件夹
                String filename = FilenameUtils.getExtension(parentResources.getResourcesName());
                String resourcesName = FilenameUtils.getExtension(resources.getResourcesName());
                if(!StringUtils.isEmpty(filename) && StringUtils.isEmpty(resourcesName)){//文件名----->>>>>文件夹
                    //1)、删除sftp上的文件
                    try {
                        sysFileService.remove(parentResources.getPath());
                    }catch (Exception e){}
                    //2)、创建文件夹
                    channelSftp.mkdir(parentResources.getFileName()+resources.getResourcesName());
                    channelSftp.exit();
                    //3)、保存数据库
                    parentResources.setResourcesName(resources.getResourcesName());
                    parentResources.setPath(parentResources.getFileName()+resources.getResourcesName());
                    parentResources.setIsDirectory((byte)0);
                    parentResources.setLastModifiedDate(System.currentTimeMillis());
                    resourcesDao.update(parentResources);
                }else if(StringUtils.isEmpty(filename) && !StringUtils.isEmpty(resourcesName)){//文件夹--->>>文件名
                    //1)、删除sftp文件夹;如果存在子集;则不让修改文件夹为文件名
                    int sum = resourcesDao.selectResourcesFolder(parentResources);
                    if(sum > 1){
                        resul.setCode(ResourcesExceptionEnum.RESOURCES_EXISTS_NAME_FAILED.getCode());
                        resul.setMessage(ResourcesExceptionEnum.RESOURCES_EXISTS_NAME_FAILED.getMsg());
                        return resul;
                    }
                    sysFileService.removeDir(parentResources.getPath());
                    //2)、生成文件;并上传到sftp
                    String fielPath = System.getProperty("java.io.tmpdir")+ File.separator + tmpRes;
                    File file = new File( fielPath);
                    if(!file.exists()) file.mkdir();
                    String path = fielPath + System.currentTimeMillis()+"."+resourcesName;
                    IOUtils.write("", new FileOutputStream(new File(path)));
                    String resourcesBaseName =  FilenameUtils.getBaseName(resources.getResourcesName());
                    String baseName = combineResourceName(resourcesBaseName);  //FilenameUtils.getBaseName(resources.getResourcesName());

                    sysFileService.upload(baseName,resourcesName,parentResources.getFileName(),IOUtils.toInputStream(path));//上传文件
                    //3）、保存数据库
                    parentResources.setResourcesName(resources.getResourcesName());
                    parentResources.setResourcesAlias(MD5Utils.getMd5ByResources());
                    parentResources.setPath(parentResources.getFileName()+baseName);
                    parentResources.setLastModifiedDate(System.currentTimeMillis());
                    parentResources.setIsDirectory((byte)1);
                    resourcesDao.update(parentResources);
                }else{//文件夹--->>>>文件夹
                    String parentPath = parentResources.getFileName();//父级路径
                    String newFilePath = parentPath.substring(0,parentPath.lastIndexOf("/")) +"/"+ resources.getResourcesName();
                    channelSftp.rename(parentResources.getFileName(),newFilePath);
                    channelSftp.exit();

                    resources.setPath(newFilePath);
                    List<Resources> childTempletLists = resourcesDao.selectContainPathFolder(resources);
                    childTempletLists.add(parentResources);
                    List<Resources>  newChildTempletLists = new ArrayList<>();

                    for(Resources child : childTempletLists){
                        String childPath = child.getPath();
                        String childFileName = child.getFileName();

                        String newPath = newFileName(childPath, newFilePath);
                        newPath = newPath.substring(0, newPath.length()-1);
                        child.setPath(newPath);
                        child.setLastModifiedDate(System.currentTimeMillis());
                        if(child.getResourcesId().equals(resources.getResourcesId())) {
                            child.setResourcesName(resources.getResourcesName());
                            child.setFileName(newFilePath);
                        }else{
                            child.setResourcesName(child.getResourcesName());
                            String newFileName = newFileName(childFileName, newFilePath);
                            child.setFileName(newFileName);
                        }
                        resourcesDao.update(child);
                    }
                }
            }else{
                if(resources.getIsDirectory()==1) {
                    Resources resources1 = resourcesDao.get(resources.getResourcesId());
                    if(resources1 == null){
                        resul.setCode(ResourcesExceptionEnum.RESOURCES_NOT_MSG.getCode());
                        resul.setMessage(ResourcesExceptionEnum.RESOURCES_NOT_MSG.getMsg());
                        return resul;
                    }
                    //标题和内容都未做调整;则直接返回
                    if(resources1.getSource().equals(resources.getSource()) && resources.getResourcesName().equals(resources1.getResourcesName())){
                        resul.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
                        resul.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
                        return resul;
                    }
                    String resourcesBaseName =  FilenameUtils.getBaseName(resources.getResourcesName());
                    String fileName = combineResourceName(resourcesBaseName);
                    SysFile sysFile = null;
                    String extension = FilenameUtils.getExtension(resources.getResourcesName());
                    if(resources.getSource().equals(resources1.getSource())){//内容未做调整而标题调整 css-js则删除老文件重新生成; 如果内容做调整;则重新生成
                        /***sysFileService.remove(resources1.getPath());
                         resources.setResourcesAlias(resources1.getResourcesAlias());*/
                        sysFile = writeHTMLFile(fileName+"."+extension, resources.getSource(), resources.getSiteId(), resources1.getFileName());//覆盖目录文件,并且重新写入
                    }else{
                        resources.setResourcesAlias(MD5Utils.getMd5ByResources());
                        sysFile = writeHTMLFile(fileName+"."+extension, resources.getSource(), resources.getSiteId(), resources1.getFileName());//覆盖目录文件,并且重新写入
                    }
                    if(null == sysFile.getFileSize())
                        resources.setSize(Long.valueOf(resources1.getSource().length()));//单位为KB
                    else
                        resources.setSize(sysFile.getFileSize());//单位为KB
                    if (sysFile.getFilePath() != null) {
                        String filePath = sysFile.getFilePath().substring(0, sysFile.getFilePath().lastIndexOf("/") + 1);
                        String sysFileFilePath = sysFile.getFilePath();
                        if(sysFileFilePath.startsWith(basePath)) {
                            sysFileFilePath = sysFileFilePath.substring(fileRoot.length(), sysFileFilePath.length());
                            resources.setPath(sysFileFilePath);
                        }else{
                            //sysFileFilePath = sysFileFilePath.substring(uploadPath.length(), sysFileFilePath.length());
                            resources.setPath(sysFileFilePath);
                        }
                        resources.setFileName(filePath);
                    }
                    resources.setLastModifiedDate(System.currentTimeMillis());
                    resourcesDao.update(resources);
                }else if(resources.getIsDirectory() ==2){
                    resul = saveUploadContent(resources);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error("资源文件重命名失败!");
            resul.setCode(ResourcesExceptionEnum.RESOURCES_MODIFY_ERROR.getCode());
            resul.setMessage(ResourcesExceptionEnum.RESOURCES_MODIFY_ERROR.getMsg());
            return resul;
        }finally {
            sftpStorage.getSftpPool().returnClient(channelSftp);
        }
        resul.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
        resul.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
        return resul;
    }


    private  String newFileName(String oldPath , String newPath){
        int newlength = newPath.split("/").length;
        int oldLength = oldPath.split("/").length;
        StringBuffer sb = new StringBuffer();
        for(int a = 0 ; a < newlength ; a++){
            sb.append("/");
            sb.append(newPath.split("/")[a]);
        }
        for(int b = newlength ; b < oldLength ; b++){
            sb.append("/").append(oldPath.split("/")[b]);
        }
        sb.append("/");
        return sb.toString().substring(1, sb.toString().length());
    }



    @Override
    public ResultDataStruct<Resources> get(Resources resources) throws Exception {
        ResultDataStruct resultDataStruct = new ResultDataStruct();
        try{
            Resources resources1 = resourcesDao.get(resources.getResourcesId());
            resultDataStruct.setData(resources1);
        }catch(Exception e){
            e.printStackTrace();
        }
        return resultDataStruct;
    }


    @Override
    public ResultMessageStruct remove(Resources resources) throws Exception {
        ResultMessageStruct resul = new ResultMessageStruct();
        try{
            //判断是否文件夹;如果是则判断是否包含子文件;有则不允许删除
            int count = resourcesDao.selectChildResources(resources);
            if (count > 0) {
                resul.setCode(ResourcesExceptionEnum.RESOURCES_EXISTS_ERROR.getCode());
                resul.setMessage(ResourcesExceptionEnum.RESOURCES_EXISTS_ERROR.getMsg());
                return resul;
            }
            Resources resources1 =  resourcesDao.get(resources.getResourcesId());
            if(resources1 != null && resources1.getIsDirectory() != 0) {//文件
                try {
                    sysFileService.remove(fileRoot+resources1.getPath());
                }catch (Exception e){}
            }else {//文件夹
                String resourcesPath = resources1.getPath();
                resourcesPath = resourcesPath.substring(0,resourcesPath.length());
                Vector<ChannelSftp.LsEntry> lsEntryVector =   sysFileService.ls(resources1.getPath());
                for(ChannelSftp.LsEntry ls : lsEntryVector){
                    sysFileService.remove(resourcesPath+ls.getFilename());
                }
                sysFileService.removeDir(resourcesPath);
            }
            resourcesDao.delete(resources.getResourcesId());
        }catch(Exception e){
            e.printStackTrace();
            resul.setCode(ResourcesExceptionEnum.RESOURCES_DELETE_ERROR.getCode());
            resul.setMessage(ResourcesExceptionEnum.RESOURCES_DELETE_ERROR.getMsg());
            return resul;
        }
        resul.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
        resul.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
        return resul;
    }


    @Override
    public ResultDataStruct<Resources> saveUploadContent(Resources resources) {
        ResultDataStruct<Resources> resultDataStruct = new ResultDataStruct<>();
        FileType[] pics = {FileType.JPEG, FileType.PNG, FileType.GIF, FileType.TIFF, FileType.BMP, FileType.DWG, FileType.PSD,FileType.JPG,FileType.ICO};
        String filePath =  System.getProperty("java.io.tmpdir");
        if(filePath.indexOf("tmp") != -1){
            filePath +=  "/"+tmpRes;
        }else{
            filePath += tmpRes.replace("/","\\");
        }
        try{
            File file = new File(filePath);
            if(!file.exists()) file.mkdir();
            String downloadPath =filePath +System.currentTimeMillis()+"."+FilenameUtils.getExtension(resources.getPath());
            boolean flag = true;
            if(fileRoot.startsWith(basePath)) {
                flag = sysFileService.downLoad(fileRoot + resources.getPath(), new FileOutputStream(downloadPath));
            }else{
                flag = sysFileService.downLoad(resources.getPath(), new FileOutputStream(downloadPath));
            }
            if(!flag){
                resultDataStruct.setData(null);
                resultDataStruct.setCode(ResourcesExceptionEnum.RESOURCES_UPLOAD_FAILED.getCode());
                resultDataStruct.setMessage(ResourcesExceptionEnum.RESOURCES_UPLOAD_FAILED.getMsg());
                return resultDataStruct;
            }
            //读取文件,重新写入sources字段
            List<String>  sourcesList = IOUtils.readLines(new FileInputStream(new File(downloadPath)));
            long sizedata  = FileUtils.sizeOf(new File(downloadPath));
            if(resources.getResourcesId()!=null){//上传覆盖原文件
                //判断如果是文件;则直接读取;如果是图片,则不读取直接保存路径
                if(sourcesList != null && sourcesList.size() >0) {
                    String path = resources.getPath();
                    Resources resources1 = resourcesDao.get(resources.getResourcesId());
                    String filename = path.substring(path.lastIndexOf("/") + 1, path.length());
                    Resources parentTemplet = new Resources();
                    if (resources.getParentId() != -1) {
                        parentTemplet = resourcesDao.get(resources.getParentId());
                    } else {
                        parentTemplet.setFileName(uploadPath);
                    }
                    String name = FilenameUtils.getExtension(filename);
                    int type = getType(name);
                    if(type==2) {
                        String resourcesName = MD5Utils.getMd5ByResources();
                        SysFile sysFile = sysFileService.upload(resourcesName, FilenameUtils.getExtension(path), resources.getFileName(), IOUtils.toInputStream(downloadPath));//重新上传
                        if(fileRoot.startsWith(basePath)) {
                            sysFileService.remove(fileRoot + resources.getPath());//删除upload方法上传文件
                        }else{
                            sysFileService.remove( resources.getPath());//删除upload方法上传文件
                        }
                        resources1.setResourcesName(filename);
                        resources1.setFileName(parentTemplet.getFileName());
                        resources1.setPath(resources.getPath());
                    }else{
                        resources1.setResourcesName(filename);
                        resources1.setFileName(parentTemplet.getFileName());
                        resources1.setPath(resources.getPath());
                    }
                    if (type == 1 || type == 2) {
                        resources1.setSource(parentTemplet.getFileName()+"/" + filename);
                        resources1.setIsDirectory((byte)type);
                    } else {
                        String sources = sourcesList.get(0);
                        resources1.setSource(sources);
                        resources1.setIsDirectory((byte)0);
                    }
                    if(!resources1.getSource().equals(resources.getSource())) resources1.setResourcesAlias(MD5Utils.getMd5ByResources());
                    resources1.setSize(sizedata);
                    resourcesDao.update(resources1);
                    resultDataStruct.setData(resources);
                    resultDataStruct.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
                    resultDataStruct.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
                }
            }else{
                if(sourcesList != null && sourcesList.size() >0){
                    //获取父级的目录;如果为-1;则为uploadPath目录路径
                    Resources parentTemplet = new Resources();
                    if(resources.getParentId() != -1) {
                        parentTemplet = resourcesDao.get(resources.getParentId());
                    }else{
                        parentTemplet.setFileName(uploadPath);
                    }
                    String path = resources.getPath();
                    String filename = path.substring(path.lastIndexOf("/")+1, path.length());
                    resources.setResourcesName(filename);
                    resources.setFileName(parentTemplet.getPath());
                    String name = FilenameUtils.getExtension(filename);
                    int type = getType(name);
                    if(type!=2) {
                        String resourcesName = MD5Utils.getMd5ByResources();
                        SysFile sysFile = sysFileService.upload(resourcesName, FilenameUtils.getExtension(path), resources.getFileName(), IOUtils.toInputStream(downloadPath));//重新上传
                        if(resources.getPath().startsWith(basePath)) {
                            sysFileService.remove(fileRoot + resources.getPath());//删除upload方法上传文件
                        }else{
                            sysFileService.remove(  resources.getPath());//删除upload方法上传文件
                        }
                        String prefixPath = sysFile.getFilePath();
                        String filenamePath = prefixPath.substring(fileRoot.length(), prefixPath.length());
                        resources.setPath(filenamePath);
                    }else{
                        //InputStream is = new FileInputStream(new File(downloadFile));
                        String parentPath = parentTemplet.getPath();
                        if(resources.getPath().startsWith(basePath)) {
                            parentPath = parentPath.substring(fileRoot.length() + 1, parentPath.length() - 1);
                        }
                        SysFile sysFile = sysFileService.upload(FilenameUtils.getBaseName(filename),name,parentPath,new FileInputStream(new File(downloadPath)));
                        //删除临时目录文件
                        String tmp = System.getProperty("java.io.tmpdir");
                        if(tmp.equals("/tmp")) {//Linux系统
                            sysFileService.remove(downloadPath);
                        }else {//window系统
                            new File(downloadPath).delete();
                        }
                        String sysFilePath = sysFile.getFilePath();
                        if(null != sysFilePath && sysFilePath.startsWith(basePath)){
                            sysFilePath = sysFilePath.substring(fileRoot.length()+1,sysFilePath.length());
                        }
                        resources.setPath("/"+sysFilePath);
                    }

                    if(type == 1 || type == 2){
                        resources.setSource(parentTemplet.getFileName()+filename);
                        resources.setIsDirectory((byte)type);
                    }else{
                        String sources = sourcesList.get(0);
                        resources.setIsDirectory((byte)0);
                        resources.setSource(sources);
                    }
                    resources.setSize(sizedata);
                    resourcesDao.save(resources);
                    resultDataStruct.setData(resources);
                    resultDataStruct.setMessage(ResourcesSuccessEnum.RESOURCES_SUCCESS.getMsg());
                    resultDataStruct.setCode(ResourcesSuccessEnum.RESOURCES_SUCCESS.getCode());
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            resultDataStruct.setCode(ResourcesExceptionEnum.RESOURCES_ADD_ERROR.getCode());
            resultDataStruct.setMessage(ResourcesExceptionEnum.RESOURCES_ADD_ERROR.getMsg());
        }
        return resultDataStruct;
    }


    /***
     * 获取文件格式类型
     * @param name  格式名称
     * ***/
    protected int getType(String name){
        FileType[] pics = {FileType.JPEG, FileType.PNG, FileType.GIF, FileType.TIFF, FileType.BMP, FileType.DWG, FileType.PSD,FileType.JPG,FileType.ICO};

        int type = 0;
        for (FileType fileType : pics) {
            if (fileType.getValue().equals(name.toUpperCase())) {
                type = 2;
                break;
            }
        }

        FileType[] csss = {FileType.CSS};
        for (FileType fileType : csss) {
            if (fileType.getValue().equals(name.toUpperCase())) {
                type = 1;
                break;
            }
        }

        FileType[] jss = {FileType.JS};
        for (FileType fileType : jss) {
            if (fileType.getValue().equals(name.toUpperCase())) {
                type = 1;
                break;
            }
        }
        return type;
    }


    @Override
    public ResultDataStruct<List<Resources>> getResourcesBySiteId(Resources resource) {
        ResultDataStruct resultDataStruct = new ResultDataStruct();
        try{
            resultDataStruct.setCode(200);
            resultDataStruct.setData(resourcesDao.get(resource));
        }catch(Exception e){
            e.printStackTrace();
            resultDataStruct.setCode(405);
        }
        return resultDataStruct;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessageStruct modifyResourcesMd5(Resources resources) throws Exception{
        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
        List<Resources> resourcesList = resourcesDao.get(resources);
        for (Resources res:resourcesList) {
            if (StringUtils.isNotBlank(res.getResourcesAlias())){continue;}
            String md5Name = MD5Utils.getMd5ByResources();
            res.setResourcesAlias(md5Name);
            int b = resourcesDao.update(res);
            if (b == 0){
                resultMessageStruct.setCode(301);
                resultMessageStruct.setMessage("添加资源文件MD5值失败");
                return resultMessageStruct;
            }
        }
        resultMessageStruct.setCode(200);
        return resultMessageStruct;
    }

    public List<Resources> selectContainPathFolder(Resources resources){
        return resourcesDao.selectContainPathFolder(resources);
    }

    //生成随机数字和字母,
    public String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
    public String combineResourceName(String name){
        if(name.indexOf("_") < 0) {
            return name = name +"_" +getStringRandom(5);
        }
        String names[] = name.split("_");
        return names[0]+"_"+getStringRandom(5);
    }

}
